# coding：utf-8
from flask import render_template, jsonify, send_from_directory, request
import os


from app import app

DOWNLOAD_MKDIR = './download/'

@app.route('/hello')
def hello_world():
    return 'Hello World!'

@app.route('/')
def index():
    return render_template('index.html', name='index')

@app.route('/file_list')
def file_list():
    # 获取文件名
    file_names = os.listdir(DOWNLOAD_MKDIR)
    # 文件名拼接路径
    return jsonify({'code': 1, 'msg': 'success', 'data':file_names})

@app.route("/download/<string:file_name>")
def download(file_name):
    return send_from_directory(DOWNLOAD_MKDIR, filename=file_name, as_attachment=True)

@app.route('/upload', methods=['POST'], strict_slashes=False)
def upload():
    if 'file' in request.files:
        f = request.files['file']
        f_name = f.filename
        if f_name[-1:] == '"':
            f_name = f_name[:-1]
        file_dir = os.path.join(os.getcwd(), r'download')
        file_path = os.path.join(file_dir, f_name)
        f.save(file_path)
        return jsonify({"code": 1, "msg": "success"})
    return jsonify({"code": 0, "msg": "error"}), 401
